import json
from flask import Blueprint, request, jsonify, g
import random
import re

import decorators
from services.userService import sendEmailCode, checkUsernameValuable, checkEmailCanUse, checkCodeValid, \
    registerNewUser, checkLogin, queryOneUserInfo, userLogout
import utils.regexEnum as reEnum

bp = Blueprint("user", __name__, url_prefix="/user")


@bp.route("/login", methods=["POST"])
def login():
    data = json.loads(request.data)
    username, password = data.get('username'), data.get('password')
    return checkLogin(username, password)


@bp.route("/register", methods=['POST'])
def register():
    data = json.loads(request.data)
    username, password, email, validcode = data.get('username'), data.get('password'), data.get('email'), data.get(
        'validcode')
    if not checkCodeValid(email, validcode):
        return jsonify({'message': '验证码不正确', 'code': 1005})
    if not checkUsernameValuable(username):
        return jsonify({'message': '用户名已被使用', 'code': 1004})
    if registerNewUser(username, password, email):
        return jsonify({'to': "/manager", 'code': 2001})
    else:
        return jsonify({'message': '未知错误', 'code': 9999})


@bp.route("/mailvalid", methods=["GET"])
def mailvalid():
    mailpath = request.args.get("email")
    # t = re.match(reEnum.EMAIL_SINGLE_REGEX, mailpath)
    # print(t.group())
    if not mailpath or re.match(reEnum.EMAIL_SINGLE_REGEX, mailpath).group() == '':
        return jsonify({"message": '邮箱格式不正确', 'code': 1001})
    if not checkEmailCanUse():
        return jsonify({'message': '邮箱已被注册', 'code': 1003})
    validcode = "%04d" % random.randint(0, 9999)
    return sendEmailCode(validcode, mailpath)


@decorators.login_reqiured
@bp.route("/info", methods=["GET"])
def reqUserInfo():
    i = queryOneUserInfo(g.user_id)
    if i is None:
        return jsonify({'to': '/login', 'code': 2001})
    return jsonify({'name': i.get('name'), 'email': i.get("email"), 'phone': i.get("phone"), 'avatar': i.get("avatar")})


@bp.route("/logout", methods=["POST"])
def logout():
    userLogout()
    return jsonify({'to': '/login', 'code': 2001})
